package com.example.androidcomplete0102.ch17;

import java.io.Serializable;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;



public class SaveCurve extends Activity {
	FreeLine vw;
	ArrayList<Vertex> arVertex;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		vw = new FreeLine(this);
		setContentView(vw);
		
		if(savedInstanceState == null){
			arVertex = new ArrayList<>();
		}else{
			arVertex = (ArrayList<Vertex>) savedInstanceState.getSerializable("Curve");
		}
	}
	
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("Curve", arVertex);
	}
	
	class Vertex implements Serializable{//시리얼라이저블 할 필요 없음
		float x;
		float y;
		boolean draw;
		
		public Vertex(float x, float y, boolean draw) {
			super();
			this.x = x;
			this.y = y;
			this.draw = draw;
		}

		public float getX() {
			return x;
		}

		public void setX(float x) {
			this.x = x;
		}

		public float getY() {
			return y;
		}

		public void setY(float y) {
			this.y = y;
		}

		public boolean isDraw() {
			return draw;
		}

		public void setDraw(boolean draw) {
			this.draw = draw;
		}
	}	

	class FreeLine extends View { 
	    Paint mPaint; 
	    public FreeLine(Context context) { 
	        super(context); 
	        mPaint = new Paint(); 
	        mPaint.setColor(Color.BLACK); 
	        mPaint.setStrokeWidth(3); 
	        mPaint.setAntiAlias(true); 
	    } 
	    public void onDraw(Canvas canvas) { 
	        canvas.drawColor(0xffe0e0e0); 
	         
	        // 정점을 순회하면서 선분으로 잇는다. 
	        for (int i=0;i<arVertex.size();i++) { 
	            if (arVertex.get(i).isDraw()) { 
	                canvas.drawLine(arVertex.get(i-1).x, arVertex.get(i-1).y, arVertex.get(i).x, arVertex.get(i).y, mPaint); 
	            } 
	        } 
	    } 
	    // 터치 이동시마다 정점들을 추가한다. 
	    public boolean onTouchEvent(MotionEvent event) { 
	        if (event.getAction() == MotionEvent.ACTION_DOWN) { 
	            arVertex.add(new Vertex(event.getX(), event.getY(), false)); 
	            return true; 
	        } 
	        if (event.getAction() == MotionEvent.ACTION_MOVE) { 
	            arVertex.add(new Vertex(event.getX(), event.getY(), true)); 
	            invalidate(); 
	            return true; 
	        } 
	        return false; 
	    } 
	} 
}

